package com.stardata.liangshisq.tcslmon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.stardata.liangshisq.tcslmon.entity.*;
import com.stardata.liangshisq.tcslmon.mapper.ArchPointMapper;
import com.stardata.liangshisq.tcslmon.mapper.BizBsMapper;
import com.stardata.liangshisq.tcslmon.mapper.BizSsMapper;
import com.stardata.liangshisq.tcslmon.service.KcKscService;
import com.stardata.liangshisq.tcslmon.service.OrderInfoService;
import com.stardata.liangshisq.tcslmon.service.SysParameterService;
import com.stardata.liangshisq.tcslmon.util.CommonConstants;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * @author Samson Shu
 * @email shush@stardata.top
 * @date 2020/12/15 22:26
 */
@Service
@AllArgsConstructor
public class OrderInfoServiceImpl implements OrderInfoService {

  private final BizBsMapper bizBsMapper;
  private final BizSsMapper bizSsMapper;
  private final ArchPointMapper archPointMapper;
  private final KcKscService kcKscService;
  private final SysParameterService parameterService;

  @NotNull
  private List<BaseOrderVo> createOrderVos(List<BizBs> bsList) {
    List<Long> jumpOrderIds = KitchenQueueUtil.getInstance().getJumpOrderIds();
    List<BaseOrderVo> result = new ArrayList<>();
    for (BizBs bizBs : bsList) {
      BaseOrderVo orderVo = new BaseOrderVo();
      orderVo.setId(bizBs.getId());

      ArchPoint archPoint = archPointMapper.selectById(bizBs.getPointId());
      if (archPoint == null) continue;

      orderVo.setTableNo(archPoint.getCode());
      orderVo.setTableName(archPoint.getName());
      KcKsc kcKsc = kcKscService.getFirstByBsId(bizBs.getId());
     if(kcKsc!=null){
        orderVo.setOrderTime(kcKsc.getCallUpTime());
        orderVo.setCallUpTime(kcKsc.getCallUpTime());
        orderVo.setCallStatus(0);
      }else{
        orderVo.setOrderTime(LocalDateTime.now());
        orderVo.setCallUpTime(LocalDateTime.now());
        orderVo.setCallStatus(1);
      }
      orderVo.setIsJumped(jumpOrderIds.contains(bizBs.getId()));
      result.add(orderVo);
    }
    return result;
  }

  @Override
  @NotNull
  public List<BaseOrderVo> queryBooking(@NotNull Long shopId) {
    List<OrderScheduleVo> orderSchedules = parameterService.getListByCode(
        "scheduledOrderQueue", OrderScheduleVo.class);

    List<Long> bsIds = new ArrayList<>();
    for (OrderScheduleVo scheduleVo : orderSchedules) {
      if (!bsIds.contains(scheduleVo.getBsId())) {
        bsIds.add(scheduleVo.getBsId());
      }
    }
    if (bsIds.size()<1) return new ArrayList<>();

    QueryWrapper<BizBs> wrapper = new QueryWrapper<>();
    wrapper.in("id", bsIds);
    List<BizBs> bsList = bizBsMapper.selectList(wrapper);

    List<BaseOrderVo> result = createOrderVos(bsList);
    for (BaseOrderVo orderVo : result) {
      int index = bsIds.indexOf(orderVo.getId());
      orderVo.setScheduleTime(orderSchedules.get(index).getTime());
    }
    //这里的排序，2023年12月31日 增加按照超时时间排序
    result.sort((o1, o2) -> {
      return o1.getCallUpTime().compareTo(o2.getCallUpTime());
    });

    return result;
  }

  @Override
  @NotNull
  public List<BaseOrderVo> queryMaking(@NotNull Long shopId, boolean needPrepared) {
    List<Long> bsIds;
    if (needPrepared) {
      //配菜完成的订单，总是在还未完全配菜的订单之前
      bsIds = parameterService.getListByCode("preparedOrderQueue", Long.class);
      bsIds.addAll(parameterService.getListByCode("preparingOrderQueue", Long.class));
    } else {
      bsIds = parameterService.getListByCode("preparingOrderQueue", Long.class);
    }
    //2. 补充配菜窗口队列可能含有的更多订单Id（单品插队订单）
    List<String> windowNames = KitchenQueueUtil.getInstance().getPrepareWindowMames();
    for (String windowName : windowNames) {
      List<WindowItemQueueVo> windowList = parameterService.getListByCode(windowName, WindowItemQueueVo.class);
      for (WindowItemQueueVo windowItem : windowList) {
        for (Long bsId : windowItem.getBsIds()) {
          if (!bsIds.contains(bsId)) {
            bsIds.add(bsId);
          }
        }
      }
    }
    if (bsIds.size()<1) return new ArrayList<>();
    QueryWrapper<BizBs> wrapper = new QueryWrapper<>();
    wrapper.in("id", bsIds);
    List<BizBs> bsList = bizBsMapper.selectList(wrapper);

    List<BaseOrderVo> result = createOrderVos(bsList);
    //这里的排序，2023年12月31日 增加按照超时时间排序
    result.sort((o1, o2) -> {
      return o1.getCallUpTime().compareTo(o2.getCallUpTime());
    });

    return result;
  }

  @Override
  @NotNull
  public List<BaseOrderVo> queryWaiting(@NotNull Long shopId) {
    List<Long> bsIds = parameterService.getListByCode("waitingOrderQueue", Long.class);
    if (bsIds.size()<1) return new ArrayList<>();

    QueryWrapper<BizBs> wrapper = new QueryWrapper<>();
    wrapper.in("id", bsIds);
    List<BizBs> bsList = bizBsMapper.selectList(wrapper);
    //这里的排序，确保返回结果仍然是系统保存的排队顺序
    List<BaseOrderVo> result = createOrderVos(bsList);
    //这里的排序，2023年12月31日 增加按照超时时间排序
    result.sort((o1, o2) -> {
      return o1.getCallUpTime().compareTo(o2.getCallUpTime());
    });
    return result;
  }

  @Override
  public List<ProductVo> queryDetail(@NotNull Long bsId) {
    List<KcKsc> kscList = kcKscService.selectByBsId(bsId);
    List<Long> jumpItemIds = parameterService.getListByCode("jumpItemIds", Long.class);
    List<ProductVo> result = new ArrayList<>();
    for (KcKsc kcKsc : kscList) {
      ProductVo productVo = kcKscService.convertToProductVo(kcKsc);
      if (productVo != null) {
        productVo.setIsJumped(jumpItemIds.contains(kcKsc.getId()));
        productVo.setOrderTimeStr(productVo.getOrderTime().toLocalTime().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
        result.add(productVo);
      }
    }
    KitchenQueryUtil.mergeProductVo4SameBs(result);
    result.sort(new Comparator<ProductVo>() {
    	// 待传【2】、待配【1】 完成【3】按照这个顺序搞 
      @Override
      public int compare(ProductVo o1, ProductVo o2) {
    	  if(o1.getStatus()==2 && o1.getStatus()==o1.getStatus()) {
    		  return -1 ;
    	  }
        return o1.getStatus()-o2.getStatus();
      }
    });
    return result;
  }

  @Override
  public String getOrderRemark(@NotNull Long bsId) {
    String remark="";
    QueryWrapper<BizSs> bizSsQueryWrapper = new QueryWrapper<>();
    bizSsQueryWrapper.eq("bs_id", bsId);
    List<BizSs> bizSsList = bizSsMapper.selectList(bizSsQueryWrapper);
    for(BizSs item: bizSsList){
      remark = item.getSsRemark();
      if(StringUtils.isNoneBlank(remark)){
        break;
      }
    }
    return remark;
  }

  @Override
  public List<BizBs> querySendData(List<Long> bsIds) {
    LocalDateTime now = LocalDateTime.now();
    QueryWrapper<BizBs> bizWrapper = new QueryWrapper<BizBs>();
    bizWrapper.between("open_time", now.with(LocalTime.MIN), now.with(LocalTime.MAX));
    if(!bsIds.isEmpty()){
      bizWrapper.in("id", bsIds);
    }else{
      return null ;
    }
    List<BizBs> bsList = bizBsMapper.selectList(bizWrapper);
    return  bsList;
  }


}
